package main

import (
	"context"
	"fmt"
	"gitee.com/jjawesomejj/awesome-rpc/server"
	"gitee.com/jjawesomejj/awesome-rpc/services"
	"gitee.com/jjawesomejj/awesome-rpc/servicesRegister/define"
	"google.golang.org/grpc"
	"os"
	"time"
)

func main() {
	if len(os.Args) == 1 {
		s := server.GrpcServer{
			Port: 9501,
		}
		s.RegisterService(server.ServiceDesc{
			Name: "测试服务",
		}, func(rpcServer *grpc.Server) {
			define.RegisterTestServiceServer(rpcServer, &services.TestRpcServices{})
		})
		s.OnServerStart(func() {
			//tool := server.RegisterCenterTool{}
			//err := tool.RegisterToConsul(server.ConsulRegisterConfig{
			//	ConsulAddress:       "127.0.0.1:8500",
			//	ServiceName:         "awesome-rpc",
			//	ServiceHost:         "192.168.21.117",
			//	ServicePort:         s.Port,
			//	ServiceTags:         []string{"test"},
			//	HealthCheckInterval: "5s",
			//	HealthCheckUrl:      "http://192.168.21.117:9502/health",
			//})
			//if err != nil {
			//	fmt.Println(err)
			//}
			//obj:=boot.DefaultApp()
			//obj.Port=9503
			//obj.IpAddress="0.0.0.0"
			//obj.RegisterModule(func() awesomehttp.HttpHandler {
			//	return &http.HealthHandler{}
			//})
			//obj.AddRoute(awesomehttp.Route{Router: "testing",RequestMethod: awesomehttp.REQUEST_METHOD_ANY,RunFun: func(ctx *httpContext.HttpContext) interface{} {
			//	return map[string]interface{}{
			//		"name":"ffsd",
			//	}
			//}})
			//go obj.Listen()
		})
		go s.Start()
		time.Sleep(3 * time.Second)
		client := server.GrpcClient{
			Host: "127.0.0.1",
			Port: 9501,
		}
		testServiceClient, err := client.GetGrpcClient(func(conn *grpc.ClientConn) (interface{}, error) {
			return define.NewTestServiceClient(conn), nil
		})
		if err != nil {
			fmt.Errorf(err.Error())
			return
		}
		testServiceClientObj := testServiceClient.(define.TestServiceClient)
		res, err := testServiceClientObj.Add(context.Background(), &define.TestRequest{
			Number: 123,
		})
		if err != nil {
			fmt.Errorf(err.Error())
		}
		fmt.Println(res.Result)
	} else {
		tool := server.RegisterCenterTool{}
		services, _, err := tool.FindServiceFromConsul(server.ConsulServiceFindConfig{
			"127.0.0.1:8500",
			"awesome-rpc",
			"test",
		})
		if err != nil {
			fmt.Errorf(err.Error())
			return
		}
		for _, service := range services {
			address := service.Service.Address
			port := service.Service.Port
			client := server.GrpcClient{
				Host: address,
				Port: port,
			}
			testServiceClient, err := client.GetGrpcClient(func(conn *grpc.ClientConn) (interface{}, error) {
				return define.NewTestServiceClient(conn), nil
			})
			if err != nil {
				fmt.Errorf(err.Error())
				return
			}
			testServiceClientObj := testServiceClient.(define.TestServiceClient)
			res, err := testServiceClientObj.Add(context.Background(), &define.TestRequest{
				Number: 123,
			})
			if err != nil {
				fmt.Errorf(err.Error())
			}
			fmt.Println(res.Result)

		}
	}

	for true {
		time.Sleep(50 * time.Second)
	}

}
